package com.jiepos.mpos.biz.service.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.CustomServiceParamStlDao;
import com.jiepos.mpos.common.entity.App_Custom_Service_Param_StlEntity;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Service_InfEntity;
import com.jiepos.mpos.common.entity.App_Service_ParamEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 会员业务参数结算Service
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.service.service
 * @ClassName CustomServiceParamStlService
 * @history
 * @UpdateRemark []
 * @since 2017/9/27
 */
@Service
public class CustomServiceParamStlService extends BaseService{

    @Autowired
    private CustomServiceParamStlDao customServiceParamStlDao;

    @Autowired
    private ServiceParamService serviceParamService;

    /**
     * 根据条件查询机构及业务列表
     * @param pagination
     * @param appServiceInfEntity
     * @param appInsInfEntity
     * @return
     */
    public Map findByCondition(HttpServletRequest request, Pagination pagination, App_Service_InfEntity appServiceInfEntity, App_Ins_InfEntity appInsInfEntity){

        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT R.INS_UUID || ':' || DBMS_RANDOM.STRING('a',20) AS UUID, ")
                .append("        I.INS_CD || '-' || I.INS_CN_NM AS INS_CD_NAME, ")
                .append("        S.SERVICE_NO || '-' || S.SERVICE_NAME AS SERVICE_NO_NAME")
                .append("   FROM (SELECT INS_UUID, SERVICE_UUID ")
                .append("           FROM "+DBConstant.Table.T_APP_CUSTOM_SERVICE_PARAM_STL+" WHERE REC_ST != '0' ")
                .append("          GROUP BY INS_UUID, SERVICE_UUID) R, ")
                .append("        "+ DBConstant.Table.T_APP_INS_INF+" I, ")
                .append("        "+DBConstant.Table.T_APP_SERVICE_INF+" S ")
                .append("  WHERE R.INS_UUID = I.INS_UUID ")
                .append("    AND R.SERVICE_UUID = S.SERVICE_UUID ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(appServiceInfEntity.getService_no())){
            sqlBuf.append("   AND S.SERVICE_NO LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_no()+"%");
        }
        if(!StringUtils.isBlank(appServiceInfEntity.getService_name())){
            sqlBuf.append("   AND S.SERVICE_NAME LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_name()+"%");
        }
        if(!StringUtils.isBlank(appInsInfEntity.getIns_cd())){
            sqlBuf.append("   AND I.INS_CD like ? ");
            params.add("%"+appInsInfEntity.getIns_cd()+"%");
        }

        pagination.queryString = sqlBuf.toString();
        pagination = super.getDirectInsAuthSql(request, pagination, "R", null);
        //执行查询
        return customServiceParamStlDao.getPaginationMap(pagination,"R",params);
    }

    /**
     * 获取业务树(编辑)
     * @return
     */
    public List<Map<String, Object>> getServiceInfTreeEdit(String ins_uuid){
        StringBuffer sb = new StringBuffer();
        sb.append("select t1.service_uuid as \"id\",null as \"pId\",t1.service_no||'-'||t1.service_name as \"name\" from ");
        sb.append(DBConstant.Table.T_APP_SERVICE_INF).append(" t1 where 1=1 ");
        sb.append(" and t1.rec_st != '0' ");
        sb.append(" and t1.service_type in ('1') ");
        List<Map<String, Object>> serList = customServiceParamStlDao.queryForList(getOrderSql(sb.toString(), "t1"));

        StringBuffer serUuids = new StringBuffer();
        for(Map<String, Object> menu : serList){
            serUuids.append("'").append(menu.get("id")).append("'").append(",");
        }

        sb = new StringBuffer();
        sb.append("select service_param_uuid as \"id\",service_uuid as \"pId\",PARAM_NO ||'-'|| PARAM_NAME as \"name\",'p' as \"flag\" from ");
        sb.append(DBConstant.Table.T_APP_SERVICE_PARAM);
        sb.append(" WHERE service_uuid IN (").append(serUuids.substring(0, serUuids.length()-1)).append(")");
        List<Map<String, Object>> paramList = customServiceParamStlDao.queryForList(getOrderSql(sb.toString(), null));

        if(serList != null && !serList.isEmpty()){
            for(Map<String, Object> map : serList){
                map.put("open", true);
            }
        }
        //根据查询的uuid来刷新业务树选中状态
        List<String> setParamsPerIns = this.getSetParamsPerIns(ins_uuid);

        if(paramList != null && !paramList.isEmpty()){
            for(Map<String, Object> map : paramList){
                map.put("open", true);
                //判断是否需要勾选
                if(setParamsPerIns.contains(map.get("id").toString())){
                    map.put("checked",true);
                }
            }
        }
        serList.addAll(paramList);
        return serList;
    }


    /**
     * 保存会员业务参数结算数据
     * @param map
     * @param entity 业务参数结算实体
     * @return
     */
    public String saveCustomServiceParamStl(Map map, App_Custom_Service_Param_StlEntity entity){
        //保存参数数据
        /*Long serviceStlParam =  this.selectServiceStlParam(entity.getIns_uuid(),entity.getService_uuid(),entity.getService_param_uuid());*/
        if (!StringUtils.isBlank(entity.getCustom_param_uuid())) {
            //更新
            entity = (App_Custom_Service_Param_StlEntity) this.saveCommonData(entity,map,"update");
            List noChangeList = new ArrayList();
            noChangeList.add("custom_param_uuid");
            noChangeList.add("rec_crt_ts");
            customServiceParamStlDao.update(entity,noChangeList);
        }else{
            //新增
            entity = (App_Custom_Service_Param_StlEntity) this.saveCommonData(entity, map, null);
            entity.setCustom_param_uuid(IDFactoryUtil.getUUID());
            customServiceParamStlDao.save(entity);
        }
        return SystemConstant.SUCCESS;
    }
    /**
     * (业务参数设置信息)
     * 根据机构编号、业务主键、业务参数主键，会员，
     * 查询，如果存在则更新记录，如果没有则新增
     * @param ins_uuid
     * @param service_uuid
     * @return
     */
    private Long selectServiceStlParam(String ins_uuid,String service_uuid,String Service_Param_Uuid){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT T.rec_id  ")
                .append(" FROM "+ DBConstant.Table.T_APP_CUSTOM_SERVICE_PARAM_STL+" T ")
                .append("   where t.ins_uuid = ? ")
                .append("  and t.service_uuid = ?  ")
                .append(" and t.Service_Param_Uuid = ? ")
                .append(" and t.rec_st = '1' ");
        List<App_Custom_Service_Param_StlEntity> serList = customServiceParamStlDao.queryForListByParam(sqlBuf.toString(), new Object[]{ins_uuid,service_uuid,Service_Param_Uuid});
        if(!CollectionUtil.isEmpty(serList)){
            return serList.get(0).getRec_id();
        }
        return null;
    }

    /**
     * 根据机构uuid得到该机构下已设置过的业务参数集合
     * @param ins_uuid
     * @return
     */
    private List<String> getSetParamsPerIns(String ins_uuid){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT DISTINCT SERVICE_PARAM_UUID ")
                .append("   FROM  "+ DBConstant.Table.T_APP_CUSTOM_SERVICE_PARAM_STL)
                .append("  WHERE REC_ST!='0' ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(ins_uuid)){
            sqlBuf.append("  AND INS_UUID = ? ");
            params.add(ins_uuid);
        }
        //查询哪些业务参数设置过
        List<Map> list = customServiceParamStlDao.queryForList(sqlBuf.toString(),params);
        if(list == null || list.size() == 0){
            return new ArrayList<>();
        }else{
            List<String> result = new ArrayList<>();
            for (Map map : list){
                result.add(map.get("SERVICE_PARAM_UUID").toString());
            }
            return result;
        }
    }

    /**
     * 加载业务参数结算设置数据
     * @param ins_uuid
     * @param service_uuid
     * @param service_param_uuid
     * @return
     */
    public App_Custom_Service_Param_StlEntity getCustomServiceParamStlDataByUUID(String ins_uuid,String service_uuid,String service_param_uuid){
        Map<String,Object> result = new HashMap<>();

        StringBuffer sqlBuf =  getInitSql("").append(", ");
        sqlBuf.append(" CUSTOM_PARAM_UUID, ")
                .append("        INS_UUID, ")
                .append("        SERVICE_UUID, ")
                .append("        SERVICE_PARAM_UUID, ")
                .append("        SETTLE_DEBIT_MINFEE, ")
                .append("        SETTLE_DEBIT_RATE, ")
                .append("        SETTLE_DEBIT_MAXFEE, ")
                .append("        SETTLE_DEBIT_ATTACHFEE, ")
                .append("        SETTLE_CREDIT_MINFEE, ")
                .append("        SETTLE_CREDIT_RATE, ")
                .append("        SETTLE_CREDIT_MAXFEE, ")
                .append("        SETTLE_CREDIT_ATTACHFEE, ")
                .append("        FIXED_AMT, ")
                .append("        REC_ID, ")
                .append("        REC_ST, ")
                .append("        LAST_OPER_IN ")
                .append("   FROM  "+DBConstant.Table.T_APP_CUSTOM_SERVICE_PARAM_STL)
                .append("   WHERE REC_ST!='0' ")
                .append("   AND INS_UUID = ? ")
                .append("   AND SERVICE_UUID = ? ")
                .append("   AND SERVICE_PARAM_UUID = ? ");
        List<App_Custom_Service_Param_StlEntity> appCustomServiceParamStlEntities = customServiceParamStlDao.queryForListByParam(sqlBuf.toString(), ins_uuid, service_uuid, service_param_uuid);
        if(appCustomServiceParamStlEntities != null && appCustomServiceParamStlEntities.size() >0){
            return appCustomServiceParamStlEntities.get(0);
        }
        return new App_Custom_Service_Param_StlEntity();
    }

    /**
     * 刷新业务树
     * @param ins_uuid
     * @param service_param_uuids
     * @return
     */
    public String updateCustomParamStlSetTree(String ins_uuid,String service_param_uuids,Map loginUser){
        //更新参数
        customServiceParamStlDao.deleteRecord(ins_uuid,service_param_uuids,String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
        //2.增补数据入库
        if(!StringUtils.isBlank(service_param_uuids)) {
            //得到设置过的业务参数uuid结合
            List<String> savedList = getSetParamsPerIns(ins_uuid);
            //页面传过来的集合
            List<String> transList = Arrays.asList(service_param_uuids.split(","));
            //求传参过来的和现在库里的差集
            Collection<String> subtract = CollectionUtils.subtract(transList, savedList);
            if (subtract != null && subtract.size() > 0) {
                for (String service_param_uuid : subtract) {
                    App_Service_ParamEntity serviceParamEntity = serviceParamService.findByUUID(service_param_uuid);
                    if(serviceParamEntity != null){
                        //业务uuid
                        String service_uuid = serviceParamEntity.getService_uuid();
                        App_Custom_Service_Param_StlEntity entity = this.initServiceParamStlEntity(ins_uuid,service_uuid,service_param_uuid);
                        this.saveCustomServiceParamStl(loginUser,entity);
                    }
                }
            }
        }
        return SystemConstant.SUCCESS;
    }

    public App_Custom_Service_Param_StlEntity initServiceParamStlEntity(String ins_uuid,String service_uuid,String service_param_uuid){
        App_Custom_Service_Param_StlEntity entity = new App_Custom_Service_Param_StlEntity();
        entity.setIns_uuid(ins_uuid);
        entity.setService_uuid(service_uuid);
        entity.setService_param_uuid(service_param_uuid);
        //
        Double zero = new Double(0);
        entity.setSettle_debit_rate(zero);
        entity.setSettle_debit_attachfee(zero);
        entity.setSettle_debit_minfee(zero);
        entity.setSettle_debit_maxfee(zero);
        entity.setSettle_credit_rate(zero);
        entity.setSettle_credit_attachfee(zero);
        entity.setSettle_credit_minfee(zero);
        entity.setSettle_credit_maxfee(zero);
        entity.setFixed_amt(zero);
        return entity;
    }

    /**
     * 校验机构业务参数结算设置值是否有效
     * @param serviceParam
     * @param insServiceParam
     * @return
     */
    public List<String> checkInsParamStl(App_Service_ParamEntity serviceParam,App_Custom_Service_Param_StlEntity insServiceParam){
        List<String> result = new ArrayList<>();
        Double zero = new Double(0);
        //借记卡校验
        if(insServiceParam.getSettle_debit_rate() != null && serviceParam.getMin_rate() != null && zero.compareTo(insServiceParam.getSettle_debit_rate()) != 0
                && insServiceParam.getSettle_debit_rate().doubleValue() < serviceParam.getMin_rate().doubleValue()){
            result.add("借记卡扣率");
        }
        if(insServiceParam.getSettle_debit_attachfee() != null && serviceParam.getMin_attachfee() !=null && zero.compareTo(insServiceParam.getSettle_debit_attachfee()) != 0
                && insServiceParam.getSettle_debit_attachfee().doubleValue() <  serviceParam.getMin_attachfee().doubleValue()){
            result.add("借记卡附加手续费");
        }
        if(insServiceParam.getSettle_debit_minfee() !=null && serviceParam.getMin_fee() != null && zero.compareTo(insServiceParam.getSettle_debit_minfee()) != 0
                && insServiceParam.getSettle_debit_minfee().doubleValue() < serviceParam.getMin_fee().doubleValue()){
            result.add("借记卡最小手续费");
        }
        if(insServiceParam.getSettle_debit_maxfee() != null && serviceParam.getMin_maxfee()!=null && zero.compareTo(insServiceParam.getSettle_debit_maxfee()) != 0
                && insServiceParam.getSettle_debit_maxfee().doubleValue() < serviceParam.getMin_maxfee().doubleValue()){
            result.add("借记卡最大手续费");
        }
        //贷记卡校验
        if(insServiceParam.getSettle_credit_rate() != null && serviceParam.getMin_rate2() != null && zero.compareTo(insServiceParam.getSettle_credit_rate()) != 0
                && insServiceParam.getSettle_credit_rate().doubleValue() < serviceParam.getMin_rate2().doubleValue()){
            result.add("贷记卡扣率");
        }
        if(insServiceParam.getSettle_credit_attachfee() != null && serviceParam.getMin_attachfee2() !=null && zero.compareTo(insServiceParam.getSettle_credit_attachfee()) != 0
                && insServiceParam.getSettle_credit_attachfee().doubleValue() <  serviceParam.getMin_attachfee2().doubleValue()){
            result.add("贷记卡附加手续费");
        }
        if(insServiceParam.getSettle_credit_minfee() !=null && serviceParam.getMin_fee2() != null && zero.compareTo(insServiceParam.getSettle_credit_minfee()) != 0
                && insServiceParam.getSettle_credit_minfee().doubleValue() < serviceParam.getMin_fee2().doubleValue()){
            result.add("贷记卡最小手续费");
        }
        if(insServiceParam.getSettle_credit_maxfee() != null && serviceParam.getMin_maxfee2()!=null && zero.compareTo(insServiceParam.getSettle_credit_maxfee()) != 0
                && insServiceParam.getSettle_credit_maxfee().doubleValue() < serviceParam.getMin_maxfee2().doubleValue()){
            result.add("贷记卡最大手续费");
        }
        return result;
    }
}
